#!/usr/bin/env python
#Copyright (c) 2011 Isaac Dawson (WBTS Project)
#Permission is hereby granted, free of charge, to any person obtaining a copy 
#of this software and associated documentation files (the "Software"), to deal 
#in the Software without restriction, including without limitation the rights 
#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
#copies of the Software, and to permit persons to whom the Software is furnished
#to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all
#copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
#THE SOFTWARE.
from twisted.web import http

class WBTSHTTPChannel(http.HTTPChannel):
    """
    WBTSHTTPChannel a monkey hack patch, basically twisted does not keep any
    data around. So without overriding the HTTPChannel there is really no way
    of keeping track of the raw request data. What we do is override the line
    received method to create our own data buffer. Now, Keep-Alives will keep
    ALL data in the channel until the connection closes. So we need to say ok,
    when the contents finished coming in take, the # of lines from the previous
    request(s) and then split our raw data buffer to give us only /after/ those
    lines, until the end of the buffer and that will be the 'final' request.
    This is all done in allContentReceived.
    """
    def __init__(self):
        self.raw_data = []
        self.last_request = []
        self.current_len = 0
        http.HTTPChannel.__init__(self)
        
    def lineReceived(self, line):
        self.raw_data.append(line)
        http.HTTPChannel.lineReceived(self, line)
    
    def allContentReceived(self):
        length = len(self.raw_data)
        self.last_request = self.raw_data[self.current_len:length]
        self.current_len = len(self.raw_data)
        http.HTTPChannel.allContentReceived(self)